package common

import (
	"github.com/golang-jwt/jwt/v5"
	"time"
)

type MyCustomClaims struct {
	Id string `json:"id"`
	jwt.RegisteredClaims
}

// 加密key
var mySigningKey = []byte("YWNFkEsZHRuY5w5uJSNDz03oSVueGLNT") // 这个要和网关的 secret 保持一致

func CreateToken(id string) (string, error) {
	// Create the claims
	claims := MyCustomClaims{
		id,
		jwt.RegisteredClaims{
			// A usual scenario is to set the expiration time relative to the current time
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(24 * time.Hour)),
			IssuedAt:  jwt.NewNumericDate(time.Now()),
			NotBefore: jwt.NewNumericDate(time.Now()), // 签名生效时间
			Issuer:    "ichazhou.com",                 // 发行人,签名，要和网关的 key 保持一致
			//Subject:   "somebody",
			//ID:        "1",
			//Audience:  []string{},
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	ss, err := token.SignedString(mySigningKey)

	return ss, err
}

func ParseToken(tokenString string) (*MyCustomClaims, error) {
	token, err := jwt.ParseWithClaims(
		tokenString,
		&MyCustomClaims{},
		func(token *jwt.Token) (interface{}, error) {
			return mySigningKey, nil
		},
	)

	if claims, ok := token.Claims.(*MyCustomClaims); ok && token.Valid {
		//fmt.Printf("%v %v", claims.Foo, claims.RegisteredClaims.Issuer)
		return claims, nil
	} else {
		//fmt.Println(err)
		return nil, err
	}
}
